package org.andu.java_gobang.game;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.andu.java_gobang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

//这个类表示一个 "匹配器" 完成整个匹配功能额
@Component
public class Matcher {
    //创建三个匹配队列
    private Queue<User> normalQueue = new LinkedList<>();
    private Queue<User> highQueue = new LinkedList<>();
    private Queue<User> veryHighQueue = new LinkedList<>();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private RoomManager roomManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    //添加玩家到匹配队列中
    public void add(User user) {
        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.offer(user);
                //唤起等待
                normalQueue.notify();
            }
            System.out.println("把玩家 " + user.getUsername() + " 加入到了 normalQueue 中");
        } else if (user.getScore() >= 2000 && user.getScore() < 3000) {
            synchronized (highQueue) {
                highQueue.offer(user);
                highQueue.notify();
            }
            System.out.println("把玩家 " + user.getUsername() + " 加入到了 highQueue 中");
        } else {
            synchronized (veryHighQueue) {
                veryHighQueue.offer(user);
                veryHighQueue.notify();
            }
            System.out.println("把玩家 " + user.getUsername() + " 加入到了 veryHighQueue 中");
        }
    }

    //玩家点击停止匹配,需要从匹配队列中移出该玩家
    public void remove(User user) {
        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.remove(user);
            }
            System.out.println("把玩家 " + user.getUsername() + " 移出了 normalQueue 中");
        } else if (user.getScore() >= 2000 && user.getScore() < 3000) {
            synchronized (highQueue) {
                highQueue.remove(user);
            }
            System.out.println("把玩家 " + user.getUsername() + " 移出了 highQueue 中");
        }else {
            synchronized (veryHighQueue) {
                veryHighQueue.remove(user);
            }
            System.out.println("把玩家 " + user.getUsername() + " 移出了 veryHighQueue 中");
        }
    }

    public Matcher() {
        //创建三个线程,对应上面三个队列
        Thread t1 = new Thread() {
            @Override
            public void run() {
                //扫描 normalQueue
                while (true) {
                    handlerMatch(normalQueue);
                }
            }
        };
        t1.start();

        Thread t2 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(highQueue);
                }
            }
        };
        t2.start();

        Thread t3 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(veryHighQueue);
                }
            }
        };
        t3.start();
    }

    private void handlerMatch(Queue<User> matchQueue) {
        synchronized (matchQueue) {
            try {
                //1.检测队列中元素是否达到 2
                while (matchQueue.size() < 2){
                    matchQueue.wait();
                }
                //2. 尝试从队列中取出两个玩家
                User player1 = matchQueue.poll();
                User player2 = matchQueue.poll();
                System.out.println("匹配到两个玩家: " + player1.getUsername() + "&" + player2.getUsername());

                //3.获取到玩家的 websocket 会话, 目的是告诉玩家匹配成功
                WebSocketSession session1 = onlineUserManager.getFromGameHall(player1.getUserId());
                WebSocketSession session2 = onlineUserManager.getFromGameHall(player2.getUserId());

                //理论上能够匹配的一定是在线的玩家,但是为了确保万无一失,进行二次判定
                if (session1 == null) {
                    //如果player1 不在线了,就把player2 放回匹配队列中重新匹配
                    matchQueue.offer(player2);
                    return;
                }
                if (session2 == null) {
                    //同
                    matchQueue.offer(player1);
                    return;
                }

                //如果匹配的两个玩家是同一个用户 ?? 再次进行万无一失的判定
                if (session1 == session2) {
                    //把其中一个放回匹配队列
                    matchQueue.offer(player1);
                    return;
                }

                //4.将两个玩家放到一个游戏房间中
                Room room = new Room();
                roomManager.add(room,player1.getUserId(), player2.getUserId());

                //5.给玩家反馈信息: 你匹配成功了
                // 通过Websocket 给两个玩家返回一个 message:'matchSuccess'
                MatchResponse response1 = new MatchResponse();
                response1.setOk(true);
                response1.setMessage("matchSuccess");
                String json1 = objectMapper.writeValueAsString(response1);
                session1.sendMessage(new TextMessage(json1));

                MatchResponse response2 = new MatchResponse();
                response2.setOk(true);
                response2.setMessage("matchSuccess");
                String json2 = objectMapper.writeValueAsString(response2);
                session2.sendMessage(new TextMessage(json2));
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
